package quick.start.core.postq;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;

import quick.start.core.io.ObjectToFile;

public class PostQueue<T extends Task> {
	public static final String QUEUE_KEY = "QUEUE_KEY";
	public static final String POST_QUEUE = "PostQueue";
	private LinkedBlockingQueue<T> queue = new LinkedBlockingQueue<T>();
	
	 @Deprecated
    private static PostQueue sInstance;

    @Deprecated
    public static synchronized PostQueue getInstance() {
        if (null == sInstance) sInstance = retain(POST_QUEUE, QUEUE_KEY);
        return sInstance;
    }

    public boolean post(T task) {
        return !this.queue.contains(task) && this.queue.add(task);
    }

    public T peek() {
        return this.queue.peek();
    }

    public void remove(T task) {
    	this.queue.remove(task);
    }

    public void clear() {
    	this.queue.clear();
    }

    public int size() {
        return this.queue.size();
    }

    public void loop() {
        Iterator<T> it = this.queue.iterator();
        while (it.hasNext()) {
            T task = it.next();
            if (null == task || task.doTask()) it.remove();
        }
    }

    public void save(String path, String qName) throws FileNotFoundException, IOException {
        ObjectToFile.writeToFile(this.queue, path, qName);
    }

    public static <T extends Task> PostQueue<T> retain(String path, String qName) {
        LinkedBlockingQueue<T> q = null;
        q = ObjectToFile.readFromFile(LinkedBlockingQueue.class, path, qName);
        PostQueue<T> postQ = new PostQueue<T>();
        if (q != null) 
        	postQ.queue = q;
        return postQ;
    }
}
